package com.itheima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.dto.CollectionBehaviorDto;
import com.itheima.article.mapper.ApCollectionMapper;
import com.itheima.article.pojo.ApCollection;
import com.itheima.article.service.ApCollectionService;
import com.itheima.behaviour.feign.ApBehaviourEntryFeign;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-20
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private  ApCollectionMapper apCollectionMapper;

    @Autowired
    private ApBehaviourEntryFeign apBehaviourEntryFeign;
    /**
     * 收藏
     * @param dto
     */
    @Override
    public void coll(CollectionBehaviorDto dto) {
        //获取ID
        Integer userid = RequestContext.getNodeValue("id");
        //查询
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(dto.getEquipmentId(), userid);
        ApBehaviorEntry entry = entryResult.getData();
        if (entry!= null){
            QueryWrapper<ApCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entry_id",entry.getId());
            queryWrapper.eq("article_id",dto.getArticleId());
            ApCollection apCollection = apCollectionMapper.selectOne(queryWrapper);
            if(apCollection==null){
                //增加一个收藏
                apCollection = new ApCollection();
                apCollection.setEntryId(entry.getId());
                apCollection.setArticleId(dto.getArticleId());
                apCollection.setType(dto.getType());
                apCollection.setCollectionTime(LocalDateTime.now());
                apCollectionMapper.insert(apCollection);
            }else{
                //删除收藏
                apCollectionMapper.delete(queryWrapper);
            }
        }
    }
}
